package org.jsola.contract.web;

import org.jsola.contract.constant.ContractConstants;
import org.jsola.contract.dto.IssuedSealAddDTO;
import org.jsola.contract.dto.SealAddDTO;
import org.jsola.contract.dto.SealBatchDTO;
import org.jsola.contract.dto.SealUpdateDTO;
import org.jsola.contract.query.SealQuery;
import org.jsola.contract.service.ISealService;
import org.jsola.contract.vo.SealListVO;
import org.jsola.contract.vo.SealVO;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import javax.validation.Valid;


/**
 * 印章
 *
 * @author JanusMix
 */
@RestController("contractSealController")
@RequestMapping(ContractConstants.API_PATH + "/v1/seals")
public class SealController implements ISealControllerAPI {

    @Autowired
    private ISealService sealService;

    /**
     * 保存印章信息
     *
     * 该方法接收一个经过验证的印章添加数据传输对象（SealAddDTO），并将其相关的印章信息保存到系统中
     * 在保存之前，方法需要检查当前用户的权限，确保其有资格添加印章信息
     *
     * @param sealAddDTO 经过验证的印章添加数据传输对象，包含待添加的印章信息
     * @return 返回保存结果，包括一个印章视图对象（SealVO），表示新添加的印章信息
     */
    @Override
    @PostMapping
    public Result<SealVO> save(@Valid @RequestBody SealAddDTO sealAddDTO) {
        // 获取当前操作用户信息
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增印章权限校验

        // 调用服务层方法保存印章信息，并返回成功结果
        return Result.success(
                sealService.save(sealAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody SealUpdateDTO sealUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改印章权限校验

        int count = sealService.update(sealUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @PostMapping(value = "/batch")
    public Result batch(@Valid @RequestBody SealBatchDTO sealBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量操作权限校验

        // 批量操作，注意校验，有越权风险
        // 新增
        List<SealAddDTO> sealAddDTOList = sealBatchDTO.getSealAddDTOList();
        if (!CollectionUtils.isEmpty(sealAddDTOList)) {
            sealService.batchSave(sealAddDTOList, tokenUser);
        }
        // 修改
        List<SealUpdateDTO> sealUpdateDTOList = sealBatchDTO.getSealUpdateDTOList();
        if (!CollectionUtils.isEmpty(sealUpdateDTOList)) {
            sealUpdateDTOList.parallelStream().forEach(
                    sealUpdateDTO -> {
                        sealService.update(sealUpdateDTO, tokenUser);
                    }
            );
        }
        // 删除
        List<Long> deleteSealIdList = sealBatchDTO.getDeleteSealIdList();
        if (!CollectionUtils.isEmpty(deleteSealIdList)) {
            sealService.deleteByIds(tokenUser, deleteSealIdList.toArray(new Long[0]));
        }
        return Result.success();
    }


    @Override
    @DeleteMapping(value = "/{sealId}")
    public Result<Integer> delete(@PathVariable Long sealId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除印章权限校验

        int count = sealService.deleteByIds(tokenUser, sealId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody Long[] sealIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除印章权限校验

        int count = sealService.deleteByIds(tokenUser, sealIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{sealId}")
    public Result<SealVO> findById(@PathVariable Long sealId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看印章权限校验

        return Result.success(
                sealService.selectById(sealId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<SealListVO>> listAll(@Valid SealQuery sealQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看印章权限校验

        return Result.success(
                sealService.select(sealQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<SealListVO>> page(@Valid SealQuery sealQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                sealService.selectPage(sealQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping("/saveIssuedSeal")
    public Result<List<SealVO>> saveIssuedSeal(@Valid @RequestBody IssuedSealAddDTO issuedSealAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增印章权限校验

        return Result.success(
                sealService.saveIssuedSeal(issuedSealAddDTO, tokenUser)
        );
    }

}

